package com.example.demo.controller;

import org.springframework.ai.chat.client.ChatClient;
import org.springframework.ai.chat.messages.UserMessage;
import org.springframework.ai.chat.model.ChatResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import reactor.core.publisher.Flux;

import java.nio.charset.StandardCharsets;

@RestController
@RequestMapping("/ai")
public class ChatController {

    @Autowired
    private ChatClient chatClient;

    @GetMapping("/chat/{message}")
    public String chat(@PathVariable("message") String message){
        return chatClient.prompt().user(message).call().content();
    }

    @GetMapping(value = "/chat/stream/{message}", produces = MediaType.TEXT_EVENT_STREAM_VALUE)
    public Flux<String> streamChat(@PathVariable("message") String message) {
        // 解码 URL 中的中文（避免后端接收乱码）
        String decodedMessage = java.net.URLDecoder.decode(message, StandardCharsets.UTF_8);
        UserMessage userMessage = new UserMessage(decodedMessage);

        // 确保返回的 Flux 正常完成（Spring AI 会自动处理结束）
        return chatClient.prompt()
                .messages(userMessage)
                .stream()
                .content()
                // 错误时主动完成 Flux，避免连接挂起
                .onErrorResume(e -> {
                    e.printStackTrace();
                    return Flux.just("后端出错：" + e.getMessage()).concat(Flux.empty());
                });
    }
}